import { message, Modal } from 'ant-design-vue'
import { useAuthStore } from '@/store/modules/auth'

interface ErrorHandlerOption {
  code: string
  messageHandle: (msg: string) => void
}

enum AuthErrorCodes {
  AUTH_NOT_LOGIN = 'AUTH_NOT_LOGIN',
  USER_PASSWORD_NOT_MATCHED = 'USER_PASSWORD_NOT_MATCHED',
  AUTH_UNAUTHORIZED = 'AUTH_UNAUTHORIZED',
}

const AUTH_NOT_LOGIN = {
  code: 'AUTH_NOT_LOGIN',
  messageHandle: (msg) => {
    Modal.confirm({
      title: 'Confirm',
      content: '你已登出，请重新登录',
      okText: '重新登录',
      cancelText: '取消',
      onOk: () => {
        const authStore = useAuthStore()
        authStore.dispatch('resetToken').then(() => {
          location.reload()
        })
      },
    })
  },
}

const USER_PASSWORD_NOT_MATCHED = {
  code: 'USER_PASSWORD_NOT_MATCHED',
  messageHandle: (_) => {
    message.info({
      content: '用户名和密码不匹配，请重新输入。',
      type: 'error',
      duration: 3,
    })
  },
}

const AUTH_UNAUTHORIZED = {
  code: AuthErrorCodes.AUTH_UNAUTHORIZED,
  messageHandle: (msg) => {
    message.info({
      content: msg,
      duration: 3,
    })
  },
}

const UNKNOWN_EXCEPTION = {
  code: 'UNKNOWN_EXCEPTION',
  messageHandle: (msg) => {
    message.info({
      content: '系统出现异常，请联系管理员。',
      type: 'error',
      duration: 3,
    })
  },
  handle: () => {},
}

const UNKNOWN_CODE = {
  code: 'UNKNOWN_CODE',
  messageHandle: (msg) => {
    message.info({
      content: message,
      type: 'error',
      duration: 3,
    })
  },
  handle: () => {
    console.log('No handler,use default handler.')
  },
}

// const ErrorHandlers = {}

class ErrorHandlerRegister {
  private handlers: Map<string, (msg: string) => void> = new Map()
  private defaultHandler = (msg: string): void => {
    message.info({
      content: msg,
      type: 'error',
      duration: 3,
    })
  }

  register(option: ErrorHandlerOption) {
    this.handlers.set(option.code, option.messageHandle)
  }

  deRegister(code: string) {
    this.handlers.delete(code)
  }

  handleError(code: string, message: string) {
    const handler = this.handlers.get(code) || this.defaultHandler
    handler(message)
  }
}

const errorHandlerRegister = new ErrorHandlerRegister()

function registerErrorHandler(handler: ErrorHandlerOption) {
  if (handler && handler.code) {
    errorHandlerRegister.register(handler)
  }
}

function deRegisterErrorHandler(code) {
  errorHandlerRegister.deRegister(code)
}

function handleError(code, message) {
  console.log(`handle error:[${code}]`)
  errorHandlerRegister.handleError(code, message)
}

errorHandlerRegister.register(UNKNOWN_CODE)
errorHandlerRegister.register(UNKNOWN_EXCEPTION)
errorHandlerRegister.register(AUTH_NOT_LOGIN)
errorHandlerRegister.register(USER_PASSWORD_NOT_MATCHED)
errorHandlerRegister.register(AUTH_UNAUTHORIZED)

export { registerErrorHandler, deRegisterErrorHandler, handleError }
